<template>
  <!-- 回收订单  售后详情 -->
  <div>
    <el-dialog :title="title" :visible="dialogVisible" append-to-body :close-on-click-modal="false" @close="close" width="800px">
      <div v-if="dialogVisible">
        <el-descriptions title="订单信息" :column="3" border :labelStyle="{minWidth:'80px',width:'80px',textAlign:'right'}" :contentStyle="{minWidth:'100px',textAlign:'left'}" v-if="orderInfo&&orderInfo.backClueOrder">
          <el-descriptions-item label="回收编号">{{orderInfo.backClueOrder.no}}</el-descriptions-item>
          <el-descriptions-item label="游戏名称">{{orderInfo.backClueOrder.gameName}}</el-descriptions-item>
          <el-descriptions-item label="游戏账号" :span="2">{{orderInfo.backClueOrder.accountNumber}}</el-descriptions-item>
          <el-descriptions-item label="买家">{{orderInfo.backClueOrder.buyerTenantName}}</el-descriptions-item>
          <el-descriptions-item label="卖家" :span="2">{{orderInfo.backClueOrder.sellerName}}</el-descriptions-item>
          <el-descriptions-item label="回收价">
            <span style="color:red">¥{{orderInfo.backClueOrder.backAmount}}</span>
          </el-descriptions-item>
          <el-descriptions-item label="包赔费">
            <span style="color:red">¥{{orderInfo.backClueOrder.guaranteeAmount}}</span>
          </el-descriptions-item>
          <el-descriptions-item label="总金额">
            <span style="color:red">¥{{orderInfo.backClueOrder.buyerActualAmount}}</span>
          </el-descriptions-item>
        </el-descriptions>
        <div style="height:20px"></div>
        <el-descriptions title="售后申请信息" :column="3" border :labelStyle="{minWidth:'80px',width:'80px',textAlign:'right'}" :contentStyle="{minWidth:'100px',textAlign:'left'}">
          <el-descriptions-item label="售后编号">{{orderInfo.afterNo}}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{orderInfo.applicantName}}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{orderInfo.createTime}}</el-descriptions-item>
          <el-descriptions-item label="买家">{{orderInfo.buyerTenantName}}</el-descriptions-item>
          <el-descriptions-item label="卖家" v-if="orderInfo.backClueOrder">{{orderInfo.backClueOrder.sellerName}}</el-descriptions-item>
          <el-descriptions-item label="问题类型" :span="3">
            <span>{{orderInfo.applicantType}}</span>
          </el-descriptions-item>
          <el-descriptions-item label="问题描述" :span="3">
            <span style="white-space: pre;">{{orderInfo.applicantRemark}}</span>
          </el-descriptions-item>
          <el-descriptions-item label="图片附件" :span="3">
            <div class="img-box flex">
              <div v-for="(item, ind) in applicantImgArr" :key="item">
                <img :src="item" @click="review(applicantImgArr,ind)" />
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
        <div style="height:20px"></div>
        <el-descriptions v-if="guaranteeInfo&&guaranteeInfo.name" title="包赔资料" :column="3" border :labelStyle="{minWidth:'80px',width:'80px',textAlign:'right'}" :contentStyle="{minWidth:'100px',textAlign:'left'}">
          <el-descriptions-item label="卖家姓名">{{guaranteeInfo.name}}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{guaranteeInfo.idCard}}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{guaranteeInfo.phoneNumber}}</el-descriptions-item>
          <el-descriptions-item label="地址" :span="3">{{guaranteeInfo.adress}}</el-descriptions-item>
          <!-- <el-descriptions-item label="卖家" v-if="orderInfo.backClueOrder">{{orderInfo.backClueOrder.sellerName}}</el-descriptions-item> -->
          <el-descriptions-item label="家庭人员" :span="3">
            <span style="white-space: pre;">{{guaranteeInfo.familyRemark}}</span>
          </el-descriptions-item>
          <el-descriptions-item label="其他信息" :span="3">
            <span style="white-space: pre;">{{guaranteeInfo.otherRemark}}</span>
          </el-descriptions-item>
          <el-descriptions-item label="图片" :span="3">
            <div class="img-box flex">
              <div v-for="(item, ind) in baopeiImgs" :key="item">
                <img :src="item" @click="review(baopeiImgs,ind)" />
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
        <div style="height:20px"></div>
        <el-descriptions title="售后处理信息" :column="3" border :labelStyle="{minWidth:'80px',width:'80px',textAlign:'right'}" :contentStyle="{minWidth:'100px',textAlign:'left'}">
          <el-descriptions-item label="处理结果">
            <span>
              <el-tag v-if="orderInfo.afterType" :type="afterTypeList[orderInfo.afterType||1].type">{{afterTypeList[orderInfo.afterType||1].label}}</el-tag>
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="处理人">{{orderInfo.operatorName}}</el-descriptions-item>
          <el-descriptions-item label="处理时间">{{orderInfo.operatorTime}}</el-descriptions-item>

          <el-descriptions-item label="赔付金额" v-if="orderInfo.afterType==2">
            <span style="color:red">¥{{orderInfo.afterAmount}}</span>
          </el-descriptions-item>
          <el-descriptions-item label="赔付账户" :span="3" v-if="orderInfo.afterType==2&&orderInfo.buyerTenantCollection">
            <span>{{orderInfo.buyerTenantCollection}}</span>
          </el-descriptions-item>
          <el-descriptions-item label="处理说明" :span="3">
            <span style="white-space: pre;">{{orderInfo.afterRemark}}</span>
          </el-descriptions-item>
          <el-descriptions-item label="图片附件" :span="3">
            <div class="img-box flex">
              <div v-for="(item, ind) in afterImgArr" :key="item">
                <img :src="item" @click="review(afterImgArr,ind)" />
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
        <div style="height:20px"></div>
        <el-form :model="ruleForm" ref="ruleForm" :inline="true" label-width="120px" :rules="rules" class="demo-ruleForm" v-if="orderInfo.status==1&&tenantInfo&&((tenantInfo.tenantId==orderInfo.operatorTenantId&&userType == 'guarant')||(orderInfo&&orderInfo.backClueOrder&&orderInfo.backClueOrder.orderType==3))">
          <el-form-item label="处理结果:" prop="afterType">
            <el-select v-model="ruleForm.afterType" clearable>
              <el-option label="恢复账号" :value="1"></el-option>
              <el-option label="赔付号款" :value="2"></el-option>
              <el-option label="不处理" :value="3"></el-option>
            </el-select>
          </el-form-item><br />
          <el-form-item label="买家收款账户:" prop="zhanghu" v-if="ruleForm.afterType==2&&!(orderInfo&&orderInfo.backClueOrder&&orderInfo.backClueOrder.orderType==3)">
            <el-select v-model="ruleForm.zhanghu" clearable @change="zhanghuChange">
              <el-option :label="item.collectionAccountName+'('+item.collectionUserName+item.collectionAccount+')'" :value="item.id" v-for="item in bankList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="赔付金额:" prop="afterAmount" v-if="ruleForm.afterType==2">
            <el-input v-model="ruleForm.afterAmount" type="text" placeholder="请输入赔付金额"></el-input>
          </el-form-item>
          <el-form-item label="说明:" prop="afterRemark">
            <el-input style="width:500px" type="textarea" v-model="ruleForm.afterRemark" rows="3" placeholder="请详细描述你的问题..."></el-input>
          </el-form-item>
          <el-form-item label="附件图片">
            <el-upload :action="uploadImgUrl" :file-list="imgShowList" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-exceed="uploadNumber" :multiple="true" :drag="true" :on-success="handleUploadSuccess" :limit="5" :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div class="center">
          <el-button @click="close('ruleForm')">关闭</el-button>
          <template v-if="orderInfo.status==1&&tenantInfo&&((tenantInfo.tenantId==orderInfo.operatorTenantId&&userType == 'guarant')||(orderInfo&&orderInfo.backClueOrder&&orderInfo.backClueOrder.orderType==3))">
            <el-button type="danger" @click="submitForm(2)" :loading="loading">拒绝售后</el-button>
            <el-button type="primary" @click="submitForm(1)" :loading="loading">同意售后</el-button>
          </template>
          
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import onSelfApi from "@/api/retrieveManage/onSelf.js";
export default {
  name: "editPrice",
  data() {
    var priceRule = (rule, value, callback) => {
      if (value === "") {
        callback();
      } else {
        if (!this.priceReg.test(value)) {
          callback(new Error("格式不正确"));
        } else if (this.orderInfo.backClueOrder.buyerActualAmount < value) {
          callback(new Error("赔付金额不能高于买家支付金额！"));
        }
        callback();
      }
    };
    return {
      title: "售后详情",
      dialogVisible: false,
      loading: false,
      uploadImgUrl: "",
      newImages: [],
      imgFileList: [],
      imgShowList: [],
      afterTypeList: {
        1: {
          label: "恢复账号",
          type: "",
        },
        2: {
          label: "赔付号款",
          type: "success",
        },
        3: {
          label: "不处理",
          type: "danger",
        },
      },
      ruleForm: {
        id: "",
        afterType: "",
        afterAmount: "",
        afterImg: "",
        afterRemark: "",
        buyerTenantCollection: "",
        zhanghu: "",
      },
      orderInfo: {},
      bankList: [],
      ApplicantTypeList: [],

      applicantImgArr: [], //申请时附件
      afterImgArr: [], //处理后附件

      guaranteeInfo: {}, //包赔信息
      baopeiImgs: [], //包赔信息的图片

      rules: {
        afterType: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        zhanghu: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        afterAmount: [
          { required: true, message: "请输入赔付金额", trigger: "blur" },
          { validator: priceRule, trigger: "blur" },
        ],
        // afterRemark: [
        //   {
        //     required: true,
        //     message: "请输入描述",
        //     trigger: "blur",
        //   },
        // ],
      },
      userType: "",
    };
  },
  computed: {
    tenantInfo() {
      return this.$store.getters.shopInfo;
    },
  },
  created() {
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
  },
  methods: {
    open(afterId, flag) {
      this.loading = false;
      this.newImages = [];
      this.imgFileList = [];
      this.imgShowList = [];
      this.ruleForm.id = afterId;
      this.ruleForm.afterType = "";
      this.ruleForm.afterRemark = "";
      this.ruleForm.afterImg = "";
      this.ruleForm.afterAmount = "";
      // this.ruleForm.backClueOrderId = this.orderInfo.id;

      this.dialogVisible = true;
      this.getApplicantType();
      this.getbackClueOrderAfterInfo(afterId);

      if (flag == "guarant") {
        // 包赔处理
        this.userType = "guarant";
      } else {
        this.userType = "";
      }
    },
    // 查询售后订单详情
    getbackClueOrderAfterInfo(id) {
      onSelfApi.getbackClueOrderAfterInfo(id).then((res) => {
        this.orderInfo = { ...res.data };
        console.log("%c Line:251 🥒 this.orderInfo", "color:#b03734", this.orderInfo);
        this.getApplicantImgArr();
        this.getBankList(this.orderInfo.buyerTenantId);
        // 如果已经处理过一次  回显上次填写的内容  (有财务账单 说明处理过)
        if (this.orderInfo.guaranteeRefundStatus) {
          this.ruleForm.afterAmount = this.orderInfo.afterAmount || 0;
          this.ruleForm.afterType = this.orderInfo.afterType || "";
          this.ruleForm.afterRemark = this.orderInfo.afterRemark || "";
          this.ruleForm.afterImg = this.orderInfo.afterImg || "";
          if (this.orderInfo.buyerTenantCollection) {
            this.ruleForm.zhanghu = this.ruleForm.buyerTenantCollection =
              this.orderInfo.buyerTenantCollection;
          }
          if (this.ruleForm.afterImg) {
            const arr = this.ruleForm.afterImg.split(",");
            if (arr && arr.length) {
              arr.forEach((r, i) => {
                this.imgFileList.push({
                  url: r,
                  name: i,
                });
                this.imgShowList.push({
                  url: r,
                  name: i,
                });
              });
            }
          }
        }
        if (
          this.orderInfo.backClueOrder &&
          this.orderInfo.backClueOrder.guaranteeInfo
        ) {
          this.guaranteeInfo = JSON.parse(
            this.orderInfo.backClueOrder.guaranteeInfo
          );
      
          let arr = [];
          if (this.guaranteeInfo.emblemIdcardImg) {
            arr.push(this.guaranteeInfo.emblemIdcardImg);
          }
          if (this.guaranteeInfo.faceIdcardImg) {
            arr.push(this.guaranteeInfo.faceIdcardImg);
          }
          if (this.guaranteeInfo.img) {
            const arr2 = JSON.parse(this.guaranteeInfo.img);
            if (arr2 && arr2.length) {
              arr2.forEach((r) => {
                if (r.url) {
                  arr.push(r.url);
                }
              });
              arr = arr.concat(arr2);
            }
          }
          this.baopeiImgs = arr;
        }
      });
    },
    // 回显申请图片
    getApplicantImgArr() {
      if (this.orderInfo.applicantImg) {
        this.applicantImgArr = this.orderInfo.applicantImg.split(",");
      }
      if (this.orderInfo.afterImg) {
        this.afterImgArr = this.orderInfo.afterImg.split(",");
      }
    },
    // 查询售后申请的 问题类型 backOrderAfterApplicantType
    getApplicantType() {
      this.getDicts("backOrderAfterApplicantType").then((res) => {
        if (res.data && res.data.length) {
          this.ApplicantTypeList = res.data;
        }
      });
    },
    // 查询收款账户列表
    getBankList(tenantId) {
      // console.log("%c Line:181 🍔 tenantId", "color:#b03734", tenantId);
      this.loading = true;
      onSelfApi
        .getBankListByTenantId({
          tenantId: tenantId,
          accountType:1
        })
        .then((response) => {
          this.bankList = response.data;
          this.loading = false;
        });
    },
    // 选择账户
    zhanghuChange(e) {
      if (e && this.bankList.length) {
        this.bankList.forEach((r) => {
          if (r.id == e) {
            // item.collectionAccountName+'('+item.collectionUserName+item.collectionAccount+')'
            this.ruleForm.buyerTenantCollection = `${r.collectionAccountName} ${r.collectionUserName} ${r.collectionAccount}`;
            //  this.ruleForm.guaranteeTenantCollection = JSON.stringify(r)
          }
        });
      }
    },
    submitForm(flag) {
      if (flag == 2 && this.ruleForm.afterType != 3) {
        return this.$message.error("拒绝售后请选择处理结果为【不处理】！");
      }
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          let str = "确认该售后申请已处理完成了吗？";
          if (flag == 2) {
            str = "确认拒绝该售后申请吗？";
            this.ruleForm.afterAmount = "";
            this.ruleForm.buyerTenantCollection = "";
          } else {
            if (this.ruleForm.afterType == 2) {
              str =
                "你选择了赔付号款，请自行确认赔付金额是否支付。";
            }
          }
          this.$confirm(str, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              // 拼接新上传的图片
              this.ruleForm.afterImg = "";
              let newArr = [];
              if (this.imgFileList && this.imgFileList.length) {
                this.imgFileList.forEach((img) => {
                  newArr.push(img.url);
                });
              }
              if (this.newImages && this.newImages.length) {
                this.newImages.forEach((img) => {
                  newArr.push(img.response.data.filePath);
                });
              }
              this.ruleForm.afterImg = newArr.join(",");

              this.loading = true;
              if (flag == 1) {
                // 同意售后
                onSelfApi.backClueOrderAfterAgree(this.ruleForm).then((res) => {
                  this.dialogVisible = false;
                  this.$message.success(res.msg);
                  this.$parent.getList();
                });
              } else {
                // 拒绝售后
                onSelfApi
                  .backClueOrderAfterRefuse(this.ruleForm)
                  .then((res) => {
                    this.dialogVisible = false;
                    this.$message.success(res.msg);
                    this.$parent.getList();
                  });
              }
            })
            .catch(() => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 凭证图片上传成功
    handleUploadSuccess(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.newImages = fileList.filter((t) => {
          return t.url.indexOf("blob:") > -1;
        });
      }
    },
    // 凭证图片删除
    handleRemove(response, fileList, file) {
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;
      // 2.找到图片对应的索引值
      this.imgFileList.forEach(function (element, key) {
        if (element.url === filePath) {
          that.imgFileList.splice(key, 1); //回显的图片
        }
      });
      this.newImages.forEach(function (element, key) {
        if (element.url === filePath) {
          that.newImages.splice(key, 1); //新上传的图片
        }
      });
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    // 连续图片预览
    review(list, ind) {
      this.$viewerApi({
        images: list,
        options: {
          initialViewIndex: ind,
        },
      });
    },
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传5张图片");
    },
    close(formName) {
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="scss">
.img-box {
  img {
    width: 100px;
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
.center {
  margin-top: 15px;
}
::v-deep .el-dialog__body {
  padding-top: 10px !important;
}
::v-deep .el-upload-dragger {
  width: 148px;
  height: 148px;
}

.pick-dialog >>> .el-input--medium input {
  text-align: left;
}
</style>
